<link rel="stylesheet" href="../assets/font-awesome/4.7.0/css/font-awesome.min.css"/>

<!-- page specific plugin styles -->

<link rel="stylesheet" href="../assets/css/bootstrap-datepicker3.min.css"/>
<link rel="stylesheet" href="../assets/css/sweetalert.css"/>
<!-- text fonts -->
<link rel="stylesheet" href="../assets/css/fonts.googleapis.com.css"/>

<!-- ace styles -->
<link rel="stylesheet" href="../assets/css/ace.min.css" class="ace-main-stylesheet" id="main-ace-style"/>
<link rel="stylesheet" href="../assets/css/fullcalendar.min.css"/>
<link rel="stylesheet" href="../assets/css/select2.min.css"/>
<link rel="stylesheet" href="../assets/css/bootstrap.min.css"/>
<link rel="stylesheet" href="../assets/css/bootstrapValidator.min.css">
<link rel="stylesheet" href="../assets/css/style.css" />
<style>
    td.fc-widget-header tr {
        height: 40px;
    }
    .form-control {
        height: 30px
    }
    a.dealfruit-event {
        text-decoration: none;
        display:block;
        white-space:nowrap;
        overflow:hidden;
        text-overflow:ellipsis;
    }

    a.dealfruit-event:hover {
        color: red;
    }
</style>

<body style="background-color: #FFFFFF"  onload="parent.scrollTo(0, 0);">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
</div>
<div class="page-content">
    <!-- <div class="page-header">
         <h1>

         </h1>
     </div>&lt;!&ndash; /.page-header &ndash;&gt;-->

    <div class="row">
        <div class="col-xs-12">
            <div class="space"></div>
            <form class="form-inline" id="searchForm" style="padding:2px 5px">
                <div class="form-group">
                    <label>开始日期:</label>
                    <input class="form-control datepicker" type="text" id="searchStartDate" name="startDate" data-date-today-highlight="true" readonly="readonly">
                </div>
                &#12288;
                <button type="button" class="btn btn-primary btn-sm" onclick="searchAll()" style="margin-top: 1px"><i
                        class="glyphicon glyphicon-search"></i> 搜索
                </button>
            </form>
            <hr>
            <form class="form-inline" id="teaInfoForm">
                <div class="form-group" style="display: none;">
                    <label>id:</label>
                    <input class="form-control" type="text" id="teaId" name="teaId" >
                </div>
                <div class="form-group">
                    <label>姓名:</label>
                    <input type="text" id="teaName" name="teaName" style="border:0px">
                </div>
                &#12288;
                <br>
                <div class="form-group" >
                    <label>口语:</label>
                    <input type="text" id="oral" name="oral" style="border:0px">
                </div>
                &#12288;
                <div class="form-group">
                    <label>听力:</label>
                    <input type="text" id="listening" name="listening" style="border:0px">
                </div>
                &#12288;
                <div class="form-group" >
                    <label>写作:</label>
                    <input type="text" id="writing" name="writing" style="border:0px">
                </div>
                &#12288;
                <div class="form-group">
                    <label>阅读:</label>
                    <input type="text" id="reading" name="reading" style="border:0px">
                </div>
                &#12288;
            </form>
            <hr>
            <div id="calendar"></div>
        </div>
        <!-- PAGE CONTENT ENDS -->
    </div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->

<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myAddModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myAddModalLabel">添加课程</h4>
            </div>
            <div class="modal-body" style="text-align: center">
                <form class="form-horizontal" id="addCourseForm" role="form">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">考试:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="addCourseType" name="courseType" style="width: 100%;">

                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">课程:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="addClassType" name="classType" style="width: 100%;">

                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">学生:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="addStudent" name="student" style="width: 100%">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary" onclick="saveCourse()">保存</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myEditModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myEditModalLabel">修改课程</h4>
            </div>
            <div class="modal-body" style="text-align: center">
                <form class="form-horizontal" id="editCourseForm" role="form">
                    <div class="form-group" style="display: none">
                        <label class="col-sm-2 control-label">tscIds:</label>
                        <div class="col-sm-6">
                            <input class="form-control" id="editTscIds" name="tscIds">
                        </div>
                    </div>
                    <div class="form-group" style="display: none">
                        <label class="col-sm-2 control-label">classId:</label>
                        <div class="col-sm-6">
                            <input class="form-control" id="editClassId" name="classId">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">考试:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="editCourseType" name="courseType" style="width: 100%;">

                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">课程:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="editClassType" name="classType" style="width: 100%;">

                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">学生:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="editStudent" name="student" style="width: 100%">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">删除</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary" onclick="updateCourse()">保存</button>
            </div>
        </div>
    </div>
</div>

</body>
<!-- PAGE CONTENT ENDS -->
<script src="../assets/js/jquery-2.1.4.min.js"></script>
<script src="../assets/js/select2.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/sweetalert.min.js"></script>
<script src="../assets/js/bootstrapValidator.min.js"></script>
<!-- page specific plugin scripts -->
<script src="../assets/js/moment.min.js"></script>
<script src="../assets/js/fullcalendar.min.js"></script>
<script src="../assets/js/locale/zh-cn.js"></script>
<script src="../assets/js/bootstrap-datepicker.min.js"></script>
<script src="../assets/js/bootstrap-datepicker.zh-CN.js"></script>
<!-- ace scripts -->
<script src="../assets/js/ace-elements.min.js"></script>
<script src="../assets/js/ace.min.js"></script>

<script type="text/javascript">
    $.fn.modal.Constructor.prototype.enforceFocus = function () {
    };
    var teaId = getParam();
    var startDate = null;
    $('.datepicker').datepicker({
        language: "zh-CN",
        format: "yyyy-mm-dd",
        autoclose: true,
        clearBtn: true
    });
    $(function () {
        formValidator();
        $("#addModal").on("hidden.bs.modal", function () {
            document.getElementById("addCourseForm").reset();
            $("#addCourseForm").data('bootstrapValidator').destroy();
            $('#addCourseForm').data('bootstrapValidator', null);
            formValidator();
        });
        $("#editModal").on("hidden.bs.modal", function () {
            document.getElementById("editCourseForm").reset();
            $("#editCourseForm").data('bootstrapValidator').destroy();
            $('#editCourseForm').data('bootstrapValidator', null);
            formValidator();
        });
        var jsonStr = {
            crew_classTime_Arr: ["08:00~09:30", "10:00~11:30", "14:00~15:30", "16:00~17:30", "18:00~19:30"]
        };
        initTeaInfo(teaId);
        initFullCalendar(jsonStr);
        var classType = [
            {
                id: 1,
                text: '口语'
            },
            {
                id: 2,
                text: '听力'
            },
            {
                id: 3,
                text: '阅读'
            },
            {
                id: 4,
                text: '写作'
            }
        ];
        var courseType = [];
        $.ajax({
            url: '/course/getAll',
            type: 'get',
            dataType: 'json',
            async: false,
            success: function (data) {
                data = data.courseType;
                for (var i = 0; i < data.length; i++)
                    courseType.push({id: data[i].id, text: data[i].name});
                $("#addCourseType").select2({
                    minimumResultsForSearch: -1,
                    data: courseType
                });
                $("#editCourseType").select2({
                    minimumResultsForSearch: -1,
                    data: courseType
                });
            },
            error: function () {

            }
        });

        $("#addClassType").select2({
            minimumResultsForSearch: -1,
            data: classType
        });
        $("#editClassType").select2({
            minimumResultsForSearch: -1,
            data: classType
        });
    });

    var selectStart, selectEnd, eventOfClick;

    function initFullCalendar(jsonStr) {
        var crew_startDate = getDate();
        var crew_classTime_Arr = jsonStr["crew_classTime_Arr"];


        $("#calendar").fullCalendar('destroy');
        $("#calendar").fullCalendar({
            lang: "zh-cn",
            defaultView: "agendaWeek",
            selectable: true,
            selectHelper: true,
            contentHeight: 644,
            eventLimit: true,
            customButtons: {
                myCustomButton: {
                    text: "发布"
                }
            },
            buttonText: {
                today: '今天',
                month: '月视图',
                week: '周视图',
                day: '日视图'
            },
            header: {
                left: 'prev,next today myCustomButton',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            allDaySlot: false,//是否显示全天
            axisFormat: 'H:mm时',
            slotDuration: '01:00:00',
            slotLabelFormat: '第H课',
            crew_classTime_Arr: crew_classTime_Arr,
            scrollTime: '01:00:00', //滚动起始时间
            displayEventTime: false, //默认不显示事件上的时间
            minTime: '01:00:00', //最小开始时间
            maxTime: '06:00:00',//最大开始时间
            defaultTimeEventDuration: '01:00:00',
            selectOverlap: false,
            events: function (start, end, timezone, callback) {
                var date = null;
                if(startDate==null||startDate=='')
                    date = this.getDate().format('YYYY-MM-DD');
                else{
                    date = formatStamp(startDate);
                    $("#calendar").fullCalendar('gotoDate', startDate);
                    startDate = null;
                }
                $.ajax({
                    url: '/teaStuClass/getAllTeacherClass',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        currentDate: date,
                        teaId: teaId
                    },
                    success: function (result) {
                        var events = [];
                        var teaStuClassBizs = result.teaStuClassBizs;
                        $.each(teaStuClassBizs, function (i, t) {
                            var classDay = formatStamp(t.classday);
                            var fromTime = classDay + "" + t.calFtime;
                            var toTime = classDay + "" + t.calTtime;
                            events.push({
                                tscIds: t.tscIds,
                                classId: t.classId,
                                timeblockId: t.timeblockId,
                                stuIds: t.stuIds,
                                stuName: t.stuName,
                                teaId: t.teaId,
                                teaName: t.teaName,
                                classTypeId: t.classTypeId,
                                courseTypeId: t.courseTypeId,
                                courseType: t.courseType,
                                classType: t.classType,
                                title: t.courseType + '<br>' + t.classType + '<br>' + t.teaName + '<br>' + t.stuName,
                                start: fromTime,
                                end: toTime,
                                className: "dealfruit-event"
                            });
                        });
                        callback(events);
                        $("#searchStartDate").datepicker('setDate', null);
                    },
                    error: function () {

                    }
                });
            },
            select: function (start, end, allDay, jsEvent) {
                if (jsEvent.name == "agendaWeek" || jsEvent.name == "agendaDay") {
                    //加载学生
                    $("#addStudent").empty();
                    $.ajax({
                        url: '/stuAvaTime/getAvaTimeStu',
                        type: 'post',
                        data: {currentDate: $.fullCalendar.formatDate(start, "YYYY-MM-DD HH:mm")},
                        dataType: 'json',
                        async: false,
                        success: function (data) {
                            data = data.stuList;
                            var stuList = [];
                            for (var i = 0; i < data.length; i++)
                                stuList.push({id: data[i].id, text: data[i].username});
                            $("#addStudent").select2({
                                placeholder: '请选择',
                                multiple: true,
                                data: stuList
                            });
                        },
                        error: function () {

                        }
                    });
                    selectStart = start;
                    selectEnd = end;
                    $('#addModal').modal('show');
                }
            },
            eventClick: function (calEvent, jsEvent, view) {
                eventOfClick = calEvent;
                $("#editModal").modal('show');
                //加载学生
                $("#editStudent").empty();
                $.ajax({
                    url: '/stuAvaTime/getAvaTimeStu',
                    type: 'post',
                    data: {currentDate: $.fullCalendar.formatDate(calEvent.start, "YYYY-MM-DD HH:mm")},
                    dataType: 'json',
                    async: false,
                    success: function (data) {
                        data = data.stuList;
                        var stuList = [];
                        for (var i = 0; i < data.length; i++)
                            stuList.push({id: data[i].id, text: data[i].username});
                        var stuIds = calEvent.stuIds.split(',');
                        var stuName = calEvent.stuName.split(',');
                        for (var i = 0; i < stuIds.length; i++)
                            stuList.push({id: parseInt(stuIds[i]), text: stuName[i]});
                        $("#editStudent").select2({
                            placeholder: '请选择',
                            multiple: true,
                            data: stuList
                        });
                    },
                    error: function () {

                    }
                });
                $("#editTscIds").val(calEvent.tscIds);
                $("#editClassId").val(calEvent.classId);
                $("#editClassType").val(calEvent.classTypeId).trigger('change');
                $("#editCourseType").val(calEvent.courseTypeId).trigger('change');
                var stuIds = calEvent.stuIds.split(",");
                $("#editStudent").val(stuIds).trigger('change');

            },
            eventRender: function (calEvent, element, view) {
                if (view.name == "month") {
                    calEvent.title = calEvent.title.replace(/<br>/g, "-");
                }
                element.html(calEvent.title);
            }
        });
    }
    function searchAll() {
        startDate = $("#searchStartDate").datepicker('getDate');
        $("#calendar").fullCalendar('refetchEvents');
    }

    function getDate() {
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
        m = m < 10 ? "0" + m : m;
        d = d < 10 ? "0" + d : d;
        return y + "-" + m + "-" + d;
    }

    function saveCourse() {
        //开启验证
        $('#addCourseForm').data('bootstrapValidator').validate();
        if (!$('#addCourseForm').data('bootstrapValidator').isValid()) {
            return;
        }
        var courseType = $("#addCourseType").select2("data")[0].text;
        var stuList = $("#addStudent").select2("data");
        var classType = $("#addClassType").select2("data")[0].text;
        var stuStr = "";
        for (var i = 0; i < stuList.length; i++) {
            stuStr += stuList[i].id + ",";
        }
        $.ajax({
            url: '/teaStuClass/addCourse',
            type: 'post',
            data: {
                teacherid: teaId,
                studentList: stuStr,
                courseType: courseType,
                classType: classType,
                startTime: $.fullCalendar.formatDate(selectStart, "YYYY-MM-DD HH:mm"),
                endTime: $.fullCalendar.formatDate(selectEnd, "YYYY-MM-DD HH:mm")
            },
            dataType: 'json',
            success: function (result) {
                if (result.success) {
                    $("#addModal").modal('hide');
                    swal("Good Job", "添加成功", "success");
                    $("#calendar").fullCalendar('refetchEvents');
                }
                else {
                    sweetAlert("Oops...", "添加失败", "error");
                }

            },
            error: function () {
                sweetAlert("Oops...", "添加失败", "error");
            }
        });
    }

    function updateCourse() {
        $('#editCourseForm').data('bootstrapValidator').validate();
        if (!$('#editCourseForm').data('bootstrapValidator').isValid()) {
            return;
        }
        var courseType = $("#editCourseType").select2("data")[0].text;
        var stuList = $("#editStudent").select2("data");
        var classType = $("#editClassType").select2("data")[0].text;
        var stuStr = "";
        for (var i = 0; i < stuList.length; i++) {
            stuStr += stuList[i].id + ",";
        }
        $.ajax({
            url: '/teaStuClass/editCourse',
            type: 'post',
            data: {
                teacherid: teaId,
                studentList: stuStr,
                courseType: courseType,
                classType: classType,
                classId: eventOfClick.classId,
                tscIds: eventOfClick.tscIds,
                startTime: $.fullCalendar.formatDate(eventOfClick.start, "YYYY-MM-DD HH:mm"),
                endTime: $.fullCalendar.formatDate(eventOfClick.end, "YYYY-MM-DD HH:mm")
            },
            dataType: 'json',
            success: function (result) {
                if (result.success) {
                    $("#calendar").fullCalendar('refetchEvents');
                    $("#editModal").modal('hide');
                    swal("Good Job", "修改成功", "success");
                }
                else {
                    sweetAlert("Oops...", "修改失败", "error");
                }

            },
            error: function () {
                sweetAlert("Oops...", "修改失败", "error");
            }
        });
    }

    function confirmDelete() {
        swal({
                title: "Are you sure?",
                text: "是否要删除课程!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "是",
                cancelButtonText: "否",
                closeOnConfirm: false
            },
            function () {
                $.ajax({
                    url: "/teaStuClass/deleteCourse",
                    type: 'post',
                    data: {classId: eventOfClick.classId, tscIds: eventOfClick.tscIds},
                    async: false,
                    success: function (result) {
                        if (result.success) {
                            $("#calendar").fullCalendar('refetchEvents');
                            $("#editModal").modal('hide');
                            swal("Deleted!", "删除成功.", "success");
                        } else {
                            sweetAlert("Oops...", result.message, "error");
                        }
                    },
                    error: function (result) {
                        $("#editModal").modal('hide');
                        sweetAlert("Oops...", "删除失败", "error");
                    }
                });
            });
    }

    function clearForm() {
        $("#addStudent").val(null).trigger("change");
    }
    
    function getParam() {
        var url=location.search;
        var Request = new Object();
        if(url.indexOf("?")!=-1){
            var str = url.substr(1)　//去掉?号
            strs = str.split("&");
            for(var i=0;i<strs.length;i++){
                Request[strs[i ].split("=")[0]]=unescape(strs[i].split("=")[1]);
            }
        }
        return Request["teaId"];
    }

    function initTeaInfo(teaId) {
        $.ajax({
            url: '/teaStuClass/getTeaClassCount',
            type: 'post',
            data: {
                teaId: teaId
            },
            dataType: 'json',
            success: function (result) {
                if (result.success) {
                    var teaClassCount = result.teaClassCount;
                    $("#teaId").val(teaClassCount.teaId);
                    $("#teaName").val(teaClassCount.teaName);
                    $("#oral").val(teaClassCount.oralNum);
                    $("#listening").val(teaClassCount.listeningNum);
                    $("#reading").val(teaClassCount.readingNum);
                    $("#writing").val(teaClassCount.writingNum);
                }
            },
            error: function () {
                sweetAlert("Oops...", "数据加载失败", "error");
            }
        });
    }

    function formatStamp(now) {
        var date = new Date(now);
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        D = date.getDate() + ' ';
        return (Y + M + D);
    }
    function formValidator() {
        $("#addCourseForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                student: {
                    message: '学生验证失败',
                    validators: {
                        notEmpty: {
                            message: '学生不能为空'
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
            }
        });
        $("#editCourseForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                student: {
                    message: '学生验证失败',
                    validators: {
                        notEmpty: {
                            message: '学生不能为空'
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
            }
        });
    }
</script>
